package com.example.dome.config.mybatis.typehandle;

import cn.hutool.core.util.StrUtil;
import com.example.dome.common.AESUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;

@MappedTypes({String.class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class AESEncryptHandler extends BaseTypeHandler<String> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        if (StrUtil.isEmpty(parameter)) {
            ps.setNull(i, Types.VARCHAR);
        } else {
            ps.setString(i, AESUtils.encrypt(parameter));
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return decrypt(rs.getString(columnName), rs.wasNull());
    }


    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return decrypt(cs.getString(columnIndex), cs.wasNull());
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return decrypt(rs.getString(columnIndex), rs.wasNull());
    }

    //字段解密
    private String decrypt(String rs, boolean rs1) throws SQLException {
        String columnValue = rs;
        if (rs1) {
            return null;
        }
        try {
            return AESUtils.decrypt(columnValue);
        } catch (Exception e) {
            return columnValue;
        }
    }
}
